package com.sso.webflow;

import com.sso.credential.CustomCredential;
import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.web.flow.CasWebflowConstants;
import org.apereo.cas.web.flow.configurer.AbstractCasWebflowConfigurer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.webflow.definition.registry.FlowDefinitionRegistry;
import org.springframework.webflow.engine.Flow;
import org.springframework.webflow.engine.ViewState;
import org.springframework.webflow.engine.builder.BinderConfiguration;
import org.springframework.webflow.engine.builder.support.FlowBuilderServices;

/**
 * 类 {@code SomethingWebflowConfigurer}  <br> 一些自定义的webflow.
 *
 * <p>详细描述
 * <p>
 *
 * @author <a href="mailto:lz2392504@gmail.com">CN華少</a>
 * @see AbstractCasWebflowConfigurer
 * @since v1.0.0
 */
public class SomethingWebflowConfigurer extends AbstractCasWebflowConfigurer {


    public SomethingWebflowConfigurer(FlowBuilderServices flowBuilderServices,
                                      FlowDefinitionRegistry mainFlowDefinitionRegistry,
                                      ConfigurableApplicationContext applicationContext,
                                      CasConfigurationProperties casProperties) {
        super(flowBuilderServices, mainFlowDefinitionRegistry, applicationContext, casProperties);
    }

    /**
     * 重新实现初始化逻辑
     */
    @Override
    protected void doInitialize() {
        System.out.println("经过了重构的初始流程");
        // 获取到登录flow，并对其进行添加进入我们需要的逻辑。
        final Flow flow = super.getLoginFlow();
        bindCredential(flow);
    }

    /**
     * 对于原有登录flow流程配置中增加定制的Credential
     * 对于原有登录的前端视图增加captcha字段
     * @param flow
     */
    protected void bindCredential(Flow flow){

        // 1、这里我们重新绑定了Credential环节，将其原有的UsernamePasswordCredential替换为了我们做过定制的CustomCredential
        // 创建流量变量。 参数:flow—流id—id type—类型
        createFlowVariable(flow, CasWebflowConstants.VAR_ID_CREDENTIAL, CustomCredential.class);

        // 2、对于登录页面让其进行输入该验证码参数。
        // 从flow中获取到前端视图的ViewState
        final ViewState state = (ViewState)flow.getState(CasWebflowConstants.STATE_ID_VIEW_LOGIN_FORM);
        // state.getTransitions()
        // 从视图中获取到绑定的配置对象
        final BinderConfiguration binderConfiguration = getViewStateBinderConfiguration(state);
        // 将验证码添加进入配置对象中
        binderConfiguration.addBinding(new BinderConfiguration.Binding("captcha",null,true));

    }
}
